<?php

namespace App\Backend\Service;

use Exception;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Config;
use App\Backend\Service\BaseService;
class ContentModerationService  extends BaseService
{

    private $accessKeyId;
    private $accessKeySecret;
    private $regionId;
    private $endpoint;
    private $bucket;
    public function __construct()
    {
        $config = [
            'accessKeyId' => config('aliyun.access_key_id'),
            'accessKeySecret' => config('aliyun.access_key_secret'),
            'regionId' => config('aliyun.region_id'),
            "endpoint" => config('aliyun.oss.endpoint'),
            "bucket" => config('aliyun.oss.bucket'),
            'connectTimeout' => 5000,
            'timeout' => 10000,
        ];
        $this->accessKeyId=$config['accessKeyId'];
        $this->accessKeySecret=$config['accessKeySecret'];
        $this->regionId=$config['regionId'];
        $this->endpoint=$config['endpoint'];
        $this->bucket=$config['bucket'];


    }

    /**
     * 执行高级图片安全检测
     * 
     * @param string $imageUrl 图片完整URL
     * @param string $scene 检测场景（默认为postImageCheck）
     * @return array 检测结果
     */
    public function checkImageAdvanced($imageUrl, $scene = 'postImageCheck')
    {
        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;
        $regionId = $this->regionId;
        
        // 阿里云内容安全API端点
        $endpoint = "https://green-cip.{$regionId}.aliyuncs.com";
        //dd($endpoint);
        $path = '/green/image/advanced/scan';
        
        // 生成时间戳 (UTC格式)
        $timestamp = gmdate('Y-m-d\TH:i:s\Z');
        
        // 准备请求参数
        $params = [
            'service' => 'image_advanced',
            'serviceParameters' => json_encode([
                'imageUrl' => $imageUrl,
                'scenes' => [$scene]
            ]),
            'Timestamp' => $timestamp,
        ];
        // 生成请求头
        $headers = $this->generateHeaders($accessKeyId, $accessKeySecret, $regionId, $path, $params, $timestamp);
        
        try {
            $response = Http::withHeaders($headers)
                ->timeout(15)  // 15秒超时
                ->connectTimeout(5)  // 5秒连接超时
                ->asForm()
                ->post($endpoint . $path, $params);

                
            if ($response->successful()) {
                return $response->json();
            }
/*            Log::error('阿里云图片检测失败', [
                'status' => $response->status(),
                'response' => $response->body(),
                'url' => $imageUrl
            ]);*/
            
            return [
                'code' => $response->status(),
                'Message' => '阿里云图片检测失败',
                'Data' => null
            ];
            
        } catch (Exception $e) {
            Log::error('阿里云图片检测异常: ' . $e->getMessage());
            return [
                'Code' => 500,
                'Message' => $e->getMessage(),
                'Data' => null
            ];
        }
    }
    
    /**
     * 生成阿里云API请求头
     */
    private function generateHeaders($accessKeyId, $accessKeySecret, $regionId, $path, $params, $timestamp)
    {
        $nonce = Str::random(16);  // 随机数
        
        // 1. 构造规范化请求字符串
        $canonicalizedQueryString = $this->buildCanonicalQueryString($params);
        
        // 2. 构造签名字符串
        $signString = "POST\n"
            . "application/x-www-form-urlencoded\n"
            . $this->buildCanonicalHeaders($nonce, $regionId) . "\n"
            . $path . "\n"
            . $canonicalizedQueryString;
        
        // 3. 计算签名 (使用HMAC-SHA1)
        $signature = base64_encode(hash_hmac('sha1', $signString, $accessKeySecret . '&', true));
        
        // 4. 构造 Authorization 头
        $authorization = "acs {$accessKeyId}:{$signature}";
        
        return [
            'Accept' => 'application/json',
            'Content-Type' => 'application/x-www-form-urlencoded',
            'x-acs-version' => '2022-03-02',
            'x-acs-action' => 'ImageModeration',
            'x-acs-region-id' => $regionId,
            'x-acs-signature-nonce' => $nonce,
            'x-acs-signature-version' => '1.0',
            'x-acs-signature-method' => 'HMAC-SHA1',
            'Authorization' => $authorization,
            'Date' => $timestamp,
        ];
    }
    
    /**
     * 构造规范化查询字符串
     */
    private function buildCanonicalQueryString($params)
    {
        // 参数按名称排序
        ksort($params);
        
        $query = [];
        foreach ($params as $key => $value) {
            // 参数名称和值都需要URL编码
            $query[] = rawurlencode($key) . '=' . rawurlencode($value);
        }
        
        return implode('&', $query);
    }
    
    /**
     * 构造规范化头部
     */
    private function buildCanonicalHeaders($nonce, $regionId)
    {
        $headers = [
            'x-acs-action' => 'ImageModeration',
            'x-acs-region-id' => $regionId,
            'x-acs-signature-nonce' => $nonce,
            'x-acs-signature-version' => '1.0',
            'x-acs-signature-method' => 'HMAC-SHA1',
            'x-acs-version' => '2022-03-02',
        ];
        
        // 按头部名称排序
        ksort($headers);
        
        $canonicalized = [];
        foreach ($headers as $key => $value) {
            // 头部名称转为小写
            $canonicalized[] = strtolower($key) . ':' . $value;
        }
        
        return implode("\n", $canonicalized);
    }

    /**
     * 生成OSS图片URL
     * 
     * @param string $path OSS文件路径
     * @return string 完整图片URL
     */
    public function getOssImageUrl($path)
    {
        $endpoint = $this->endpoint;
        $bucket = $this->bucket;
        
        return "https://{$bucket}.{$endpoint}/" . ltrim($path, '/');
    }

    /**
     * 解析检测结果
     * 
     * @param array $result 原始检测结果
     * @return array 解析后的结果
     */
    public function parseResult($result)
    {
        dd($result);
        if (!$result) {
            return [
                'status' => 'error',
                'message' => '检测服务无响应'
            ];
        }
        
        // 检查错误代码
        if (isset($result['Code']) && $result['Code'] !== 200) {
            return [
                'status' => 'error',
                'message' => $result['Message'] ?? '检测服务错误',
                'code' => $result['Code']
            ];
        }
        
        // 获取实际检测数据
        $data = $result['Data'][0] ?? $result['data'][0] ?? null;
        dd($data);
        
        if (!$data) {
            return [
                'status' => 'error',
                'message' => '无效的检测结果',
                'details' => $result
            ];
        }

        // 提取关键信息
        $suggestion = $data['Suggestion'] ?? $data['suggestion'] ?? 'unknown';
        $label = $data['Label'] ?? $data['label'] ?? 'unknown';
        $confidence = $data['Confidence'] ?? $data['confidence'] ?? 0;

        // 映射状态
        $statusMap = [
            'pass' => 'safe',
            'review' => 'review',
            'block' => 'blocked'
        ];

        $status = $statusMap[$suggestion] ?? 'unknown';

        return [
            'status' => $status,
            'suggestion' => $suggestion,
            'label' => $label,
            'confidence' => $confidence,
            'details' => $data
        ];
    }
    
    /**
     * 文本内容安全检测
     * 
     * @param string $text 待检测文本
     * @return array 检测结果
     */
    public function checkText($text)
    {
        $accessKeyId = config('aliyun.access_key_id');
        $accessKeySecret = config('aliyun.access_key_secret');
        $regionId = config('aliyun.region_id', 'cn-shanghai');
        
        $endpoint = "https://green-cip.{$regionId}.aliyuncs.com";
        $path = '/green/text/scan';
        
        // 生成时间戳
        $timestamp = gmdate('Y-m-d\TH:i:s\Z');
        
        // 准备请求参数
        $params = [
            'service' => 'green',
            'serviceParameters' => json_encode([
                'content' => $text
            ]),
            'Timestamp' => $timestamp,
        ];
        
        // 生成请求头
        $headers = $this->generateHeaders($accessKeyId, $accessKeySecret, $regionId, $path, $params, $timestamp);
        
        try {
            $response = Http::withHeaders($headers)
                ->timeout(10)
                ->asForm()
                ->post($endpoint . $path, $params);
                
            if ($response->successful()) {
                return $response->json();
            }
            
            Log::error('阿里云文本检测失败', [
                'status' => $response->status(),
                'response' => $response->body(),
                'text' => substr($text, 0, 100) // 记录部分文本
            ]);
            
            return [
                'Code' => $response->status(),
                'Message' => 'HTTP请求失败'
            ];
            
        } catch (Exception $e) {
            Log::error('阿里云文本检测异常: ' . $e->getMessage());
            return [
                'Code' => 500,
                'Message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * 解析文本检测结果
     */
    public function parseTextResult($result)
    {
        if (!$result) {
            return [
                'status' => 'error',
                'message' => '检测服务无响应'
            ];
        }
        
        if (isset($result['Code']) && $result['Code'] !== 200) {
            return [
                'status' => 'error',
                'message' => $result['Message'] ?? '检测服务错误',
                'code' => $result['Code']
            ];
        }
        
        $data = $result['Data'][0] ?? $result['data'][0] ?? null;
        if (!$data) {
            return [
                'status' => 'error',
                'message' => '无效的检测结果'
            ];
        }

        $suggestion = $data['Suggestion'] ?? $data['suggestion'] ?? 'unknown';
        $label = $data['Label'] ?? $data['label'] ?? 'unknown';

        $statusMap = [
            'pass' => 'safe',
            'review' => 'review',
            'block' => 'blocked'
        ];

        $status = $statusMap[$suggestion] ?? 'unknown';

        return [
            'status' => $status,
            'suggestion' => $suggestion,
            'label' => $label,
            'details' => $data
        ];
    }
}
